﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.SpatialAnalyst;
using ESRI.ArcGIS.GeoAnalyst;


namespace SZ
{
    public partial class RasterClipFrm : DevExpress.XtraEditors.XtraForm
    {
        private DrawClipEnvelopTool m_DrawClipEnvelopTool = null;
        private MainFrm m_mainFrm = null;
        private AxMapControl m_mapControl = null;

        public RasterClipFrm(MainFrm mainFrm, AxMapControl mapControl)
        {
            InitializeComponent();

            m_mapControl = mapControl;
            m_mainFrm = mainFrm;

        }

        private void clipBtn_Click(object sender, EventArgs e)
        {
            if (m_DrawClipEnvelopTool == null)
            {
                m_DrawClipEnvelopTool = new DrawClipEnvelopTool(m_mainFrm, m_mapControl,this);
                m_DrawClipEnvelopTool.OnCreate(m_mapControl.Object);
                m_DrawClipEnvelopTool.OnClick();
                this.m_mapControl.CurrentTool = m_DrawClipEnvelopTool;
            }
            else
            {
                this.m_mapControl.CurrentTool = m_DrawClipEnvelopTool;
            }
        }

        private void RasterClipFrm_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < m_mapControl.Map.LayerCount; i++)
            {
                string layerName = m_mapControl.Map.get_Layer(i).Name;
                rasterLayerCom.Properties.Items.Add(layerName);
            }
            rasterLayerCom.Text = m_mapControl.Map.get_Layer(0).Name;
        }

        private void outputDirBtnEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                outputDirBtnEdit.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void ensureBtn_Click(object sender, EventArgs e)
        {
            //裁剪范围
            double topCoord, bottomCoord, leftCoord, rightCoord;
            try
            {
                topCoord = double.Parse(this.upText.Text);
                bottomCoord = double.Parse(this.downText.Text);
                leftCoord = double.Parse(this.leftText.Text);
                rightCoord = double.Parse(this.rightText.Text);
            }
            catch
            {
                MessageBox.Show("裁剪范围有误！");
                return ;
            }
            IEnvelope pEnvelop = new EnvelopeClass();
            pEnvelop.PutCoords(leftCoord, bottomCoord, rightCoord, topCoord);

            //在mapcontrol中查找需要裁切的图层
            ILayer pLayer = null;
            for (int i = 0; i < m_mapControl.LayerCount; i++)
            {
                pLayer  = m_mapControl.get_Layer(i);
                if (pLayer .Name  == rasterLayerCom.Text)
                {
                    break;
                }
            }
            if (pLayer == null)
            {
                MessageBox.Show("没有找到图层！");
                return;
            }

            //#region 影像裁剪

            //IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactoryClass();
            //IRasterWorkspace pRasterWorkspace = pWorkspaceFactory.OpenFromFile(outputDirBtnEdit.Text, 0) as IRasterWorkspace ;
            //IExtractionOp pExtractionOp = new RasterExtractionOpClass();
            //IRasterAnalysisEnvironment pRasterAnalysisEnvironment = pExtractionOp as IRasterAnalysisEnvironment;
            //object missing= Type.Missing ;

            //IRasterLayer pRasterLayer = pLayer as IRasterLayer;
            //IRaster pRaster = pRasterLayer.Raster;
            //IRasterProps pRasterProps = pRaster as IRasterProps;
            //object cellSizeProvider = pRasterProps.MeanCellSize().X;
            //IGeoDataset pGeodataset = pRaster as IGeoDataset;
            //object extentProvider = pEnvelop;
            //pRasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider);
            //pRasterAnalysisEnvironment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref missing);

            //IGeoDataset pOutputDataset = pExtractionOp.Rectangle(pGeodataset, pEnvelop, true);
            //IRaster clipRaster = null;

            //if (pOutputDataset is IRasterLayer)
            //{
            //    IRasterLayer rasterLayer = pOutputDataset as IRasterLayer;
            //    clipRaster = rasterLayer.Raster;
            //}
            //else if (pOutputDataset is IRasterDataset)
            //{
            //    IRasterDataset pRasterDataset = pOutputDataset as IRasterDataset;
            //    clipRaster = pRasterDataset.CreateDefaultRaster();

            //}
            //else if (pOutputDataset is IRaster)
            //{
            //    clipRaster = pOutputDataset as IRaster;
            //}

            //if (clipRaster != null)
            //{
            //    ISaveAs pSaveAs = clipRaster as ISaveAs ;
            //    int index = -1;
            //    index = pRasterLayer.Name.LastIndexOf("\\");
            //    string strLayerName = null;
            //    if (index != -1)
            //    {
            //        strLayerName = pRasterLayer.Name.Substring(index + 1);
            //    }
            //    string strRasterPath = outputDirBtnEdit.Text + "\\" + strLayerName.Replace('.', '_') + ".tif";
            //    pSaveAs.SaveAs(pRasterLayer.Name.Replace('.', '_') + ".tif", (IWorkspace)pRasterWorkspace, "TIFF");

            //    System.Runtime.InteropServices.Marshal.ReleaseComObject(clipRaster);
            //    GC.Collect();
            //    GC.WaitForPendingFinalizers();

            //    ////统计栅格
               
            //    IRasterDataset pRasterDataset = GetRasterDataset(strRasterPath);
            //    if (pRasterDataset != null)
            //    {
            //        RasterStatistics(pRasterDataset);
            //    }

            //    //建立影像金字塔
            //   IRasterPyramid3 pRasterPyamid3 = pRasterDataset as IRasterPyramid3 ;
            //   if (pRasterPyamid3.Present == false)
            //   {
            //       pRasterPyamid3.BuildPyramid(6, rstResamplingTypes.RSP_NearestNeighbor);
            //   }
            //   System.Runtime.InteropServices.Marshal.ReleaseComObject (pRasterDataset);
            //   GC.Collect();
            //   GC.WaitForPendingFinalizers();
            //}
            //#endregion   

            #region zc代码
            IWorkspaceFactory pWorkspaceFactory = null;
            IWorkspace pWorkspace = null;
            IFeatureWorkspace pFeatureWorkspace = null;
            IRasterWorkspace pRasterWorkspace = null;
            IExtractionOp pExtractionOp = null;
            IRasterAnalysisEnvironment pRasterAnaEnvir = null;
            IRasterLayer pRasterLayer = null;
            IRaster pRaster = null;
            IRaster clipRaster = null;
            IFeatureLayer pFeatureLayer = null;
            IFeatureClass pFeatureClass = null;
            IRasterDataset pRasterDataset = null;
            IDataset pDataset = null;
            IGeoDataset pGeoDataset = null;
            IGeoDataset pOutputDataset = null;
            IRasterProps pRasterPros = null;
            ISaveAs pSaveAs = null;
            object cellSizeProvider = null;
            object extentProvider = null;

            pWorkspaceFactory = new RasterWorkspaceFactory();
            pRasterWorkspace = (IRasterWorkspace)pWorkspaceFactory.OpenFromFile(outputDirBtnEdit.Text, 0);
            pExtractionOp = new RasterExtractionOpClass();
            pRasterAnaEnvir = pExtractionOp as IRasterAnalysisEnvironment;
            object missing = Type.Missing;
     
                try
                {
                    pRasterLayer = pLayer as IRasterLayer;
                    pRaster = pRasterLayer.Raster;
                    pRasterPros = pRaster as IRasterProps;
                    cellSizeProvider = pRasterPros.MeanCellSize().X;
                    pGeoDataset = pRaster as IGeoDataset;
                    extentProvider = pEnvelop;
                    pRasterAnaEnvir.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider);
                    pRasterAnaEnvir.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref missing);
                    pOutputDataset = pExtractionOp.Rectangle(pGeoDataset, pEnvelop, true);
                    clipRaster = null;
                    if (pOutputDataset is IRasterLayer)
                    {
                        IRasterLayer rasterLayer = pOutputDataset as IRasterLayer;
                        clipRaster = rasterLayer.Raster;
                    }
                    else if (pOutputDataset is IRasterDataset)
                    {
                        IRasterDataset rasterDataset = pOutputDataset as IRasterDataset;
                        clipRaster = rasterDataset.CreateDefaultRaster();
                    }
                    else if (pOutputDataset is IRaster)
                    {
                        clipRaster = pOutputDataset as IRaster;
                    }
                    if (clipRaster != null)
                    {
                        int index = -1;
                        index = pRasterLayer.Name.LastIndexOf("\\");
                        string strLayerName = pRasterLayer.Name;
                        if (index != -1)
                        {
                            strLayerName = pRasterLayer.Name.Substring(index + 1);
                        }
                        string strRasterPath = outputDirBtnEdit.Text + "\\" + strLayerName.Replace('.', '_') + ".tif";

                        pSaveAs = clipRaster as ISaveAs;
                        pSaveAs.SaveAs(strRasterPath, (IWorkspace)pRasterWorkspace, "TIFF");

                        System.Runtime.InteropServices.Marshal.ReleaseComObject(clipRaster);
                        GC.Collect();
                        GC.WaitForPendingFinalizers();

                        //统计栅格
                        pRasterDataset = GetRasterDataset(strRasterPath);
                        if (pRasterDataset != null)
                        {
                            RasterStatistics(pRasterDataset);
                        }

                        //建立金字塔
                        IRasterPyramid3 pRasterPyramid3 = pRasterDataset as IRasterPyramid3;
                        if (pRasterPyramid3.Present == false)
                        {
                            pRasterPyramid3.BuildPyramid(6, rstResamplingTypes.RSP_BilinearInterpolation);
                        }

                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterDataset);
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                    }
                }
                    
                catch
                {

                }
            
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pExtractionOp);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterWorkspace);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkspaceFactory);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            #endregion
    }
        
        //获得栅格数据集
        public IRasterDataset GetRasterDataset(string rasterFilePahth)
        {
            try
            {
                string str = rasterFilePahth;
                if (File.Exists(rasterFilePahth))
                {
                    IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                    IRasterWorkspace rasterWorkspace = null;
                    IRasterDataset rasterDataset = null;

                    string rasterDir = System.IO.Path.GetDirectoryName(rasterFilePahth);
                    string rasterName = System.IO.Path.GetFileName(rasterFilePahth);
                    rasterWorkspace = workspaceFactory.OpenFromFile(rasterDir, 0) as IRasterWorkspace;
                    rasterDataset = rasterWorkspace.OpenRasterDataset(rasterName);
                    return rasterDataset;
                }
                else
                    return null;
            }
            catch
            {
                return null;
            }
        }

        //计算栅格统计值
        private void RasterStatistics(IRasterDataset pRasterDataset)
        {
            try
            {
                IRasterBandCollection pRasterBandCollection = pRasterDataset as IRasterBandCollection;
                for (int i = 0; i < pRasterBandCollection.Count; i++)
                {
                    IRasterBand pRasterBand = pRasterBandCollection.Item(i);
                    pRasterBand.ComputeStatsAndHist();
                    IRasterStatistics pRasterStatistics = pRasterBand.Statistics;
                }
            }
            catch
            {
 
            }
        }








    }
}